import React, { useEffect, useRef, useState } from 'react';
import { Loader2, AlertTriangle } from 'lucide-react';

export default function MarkdownPreviewRenderer({ content, scrollContainerId }) {
  const containerRef = useRef(null);
  const [status, setStatus] = useState('loading'); // loading, loaded, error

  useEffect(() => {
    setStatus('loading');
    if (!containerRef.current) return;

    // 清空容器
    containerRef.current.innerHTML = '';
    
    const loadAndRender = () => {
      if (window.marked) {
        renderMarkdown(content);
        return;
      }

      const script = document.createElement('script');
      script.src = 'https://cdn.jsdelivr.net/npm/marked@9.1.6/marked.min.js';
      script.async = true;
      script.onload = () => {
        if (window.marked) {
          renderMarkdown(content);
        } else {
          setStatus('error');
        }
      };
      script.onerror = () => setStatus('error');
      document.body.appendChild(script);

      return () => {
        if (script.parentNode) {
          document.body.removeChild(script);
        }
      };
    };

    const cleanup = loadAndRender();
    return cleanup;

  }, [content]);

  const renderMarkdown = (markdownContent) => {
    if (containerRef.current && window.marked) {
      const renderer = new window.marked.Renderer();
      let index = 0;

      // 核心修改：重写heading渲染器，为每个标题添加唯一的ID
      renderer.heading = (text, level, rawtext) => {
        const id = `heading-${index++}-${rawtext.toLowerCase().replace(/\s+/g, '-')}`;
        return `<h${level} id="${id}">${text}</h${level}>`;
      };
      
      window.marked.setOptions({
          renderer: renderer,
          gfm: true,
          breaks: true,
          tables: true,
          smartLists: true,
      });
      containerRef.current.innerHTML = window.marked.parse(markdownContent || '');
      setStatus('loaded');
    }
  };

  return (
    <div className="markdown-body p-1">
      {status === 'loading' && (
        <div className="flex items-center justify-center p-8 text-gray-500">
          <Loader2 className="w-5 h-5 mr-2 animate-spin" />
          正在加载高级预览器...
        </div>
      )}
      {status === 'error' && (
        <div className="flex items-center justify-center p-8 text-red-600 bg-red-50 rounded-md">
          <AlertTriangle className="w-5 h-5 mr-2" />
          预览器加载失败。
        </div>
      )}
      <div ref={containerRef} style={{ display: status === 'loaded' ? 'block' : 'none' }} />
    </div>
  );
}